package com.UKIT.airtickets

import android.content.Context
import androidx.room.Room
import androidx.test.core.app.ApplicationProvider
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.UKIT.airtickets.DB.AppDatabase
import com.UKIT.airtickets.DB.User
import com.UKIT.airtickets.Service.Handlers.UserDatabaseManager
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.fail
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith

@RunWith(AndroidJUnit4::class)
class UserDatabaseManagerTest {

    private lateinit var db: AppDatabase
    private lateinit var context: Context
    private lateinit var userDatabaseManager: UserDatabaseManager

    @Before
    fun setup() {
        context = ApplicationProvider.getApplicationContext<Context>()
        db = Room.inMemoryDatabaseBuilder(context, AppDatabase::class.java).build()
        userDatabaseManager = UserDatabaseManager(context)
    }

    @After
    fun teardown() {
        db.close()
    }

    @Test
    fun getUserByLogin_Success() {
        val user = User( login = "test", email =  "test@mail.ru", password = "Password1.")
        runBlocking {
            db.userDao().addUser(user)
            val retrievedUser = userDatabaseManager.getUserByLogin("test")
            delay(100)
            if (retrievedUser != null) {
                assertEquals(user, retrievedUser)
            } else {
                fail("User not found")
            }
        }
    }

    @Test
    fun getUserByLogin_NotFound() {
        runBlocking {
            val retrievedUser = userDatabaseManager.getUserByLogin("non_existing_user")
            delay(100)
            assertEquals(null, retrievedUser)
        }
    }
}
